﻿using UnityEngine;
using System.Collections;

public class EnemyBase : MonoBehaviour {

	public static GameObject GetPlayerRef(){
		GameObject p = GameObject.FindGameObjectWithTag("Player");

		return p;
	}

	private Vector3 defaultFacingDir = -Vector3.right;
	private GameObject playerRef = null;

	public float attackRange = 1f;
	public float moveSpeed = 1f;
	public int health = 10;

	// Use this for initialization
	void Start () {
		playerRef = GetPlayerRef();
	}

	#region Sensors
	protected bool IsPlayerInRange(){
		Vector3 relativePos = playerRef.transform.position - transform.position;
		relativePos.z = 0;

		if(relativePos.sqrMagnitude < attackRange*attackRange) return true;
		return false;
	}
	#endregion

	#region Capabilitites
	protected bool MoveToPlayer(){
		if(IsPlayerInRange()) return true;

		// Orient to player and move to player
		float dir = (playerRef.transform.position - transform.position).x;
		dir /= Mathf.Abs(dir);

		Orient(dir);

		Vector3 pos = transform.position;
		pos.x += dir * moveSpeed;
		transform.position = pos;

		return false;
	}

	protected bool AttackPlayer(){
		return false;
	}

	#endregion

	#region Events
	public void Damage(int damageAmount){
		health -= damageAmount;

	}
	#endregion

	private void Orient(float dir){
		Vector3 flipScale = transform.localScale;
		flipScale.x = dir * defaultFacingDir.x;
		transform.localScale = flipScale;
	}

	void Update(){

		if(MoveToPlayer()) AttackPlayer();
	}

	void OnDrawGizmos(){
		Vector3 p = transform.position;
		p.z = 0;

		Color c = Gizmos.color;

		Gizmos.color = Color.green;
		Gizmos.DrawLine(p, p - transform.right*1f);

		Gizmos.color = Color.red;
		Gizmos.DrawWireSphere(p, attackRange);


		Gizmos.color = c;
	}
}
